﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Citi.Helpers;

namespace Citi.ConvertExcelFiles
{
    public partial class SelectFiles : Form
    {
        private enum ConvertionType
        {
            [Description("TXT to CSV")]
            TxtToCsv,
            [Description("XLSX to XLSB")]
            XlsxToXlsb,
            [Description("XLS to XLSB")]
            XlsToXlsb,
            [Description("XLS to XLSX")]
            XlsToXlsx
        }

        private IEnumerable<String> FilesInSourceFolder { get { return Directory.GetFiles(txtSource.Text); } }
        private List<String> FilesToConvert { get; set; }
        private CultureInfo cultureInfo = new CultureInfo("pt-BR");

        public SelectFiles()
        {
            InitializeComponent();
        }

        private void UpdateProgress(int actual)
        {
            var valuePerFile = 100 / FilesToConvert.Count * actual;
            lblProgress.Text = string.Format("{0} of {1} files", actual, FilesToConvert.Count());
            progressBar.Value = valuePerFile;
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(txtSource.Text))
            {
                MessageBox.Show("Source folder does not exist", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!Directory.Exists(txtDestination.Text))
            {
                MessageBox.Show("Destination folder does not exist", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Convert();
        }

        private void Convert()
        {
            progressBar.Visible = lblProgress.Visible = true;
            progressBar.Value = 0;
            lblProgress.Text = "Starting convertion";
            btnConvert.Enabled = false;

            try
            {
                switch ((ConvertionType)cboConvertionType.SelectedIndex)
                {
                    case ConvertionType.TxtToCsv:
                        ConvertTxtToCsv();
                        break;
                    case ConvertionType.XlsToXlsb:
                        ConvertXlsToXlsb(".xls");
                        break;
                    case ConvertionType.XlsToXlsx:
                        ConvertXlsToXlsx();
                        break;
                    case ConvertionType.XlsxToXlsb:
                        ConvertXlsToXlsb(".xlsx");
                        break;
                }

                progressBar.Value = 100;
                MessageBox.Show("Files successfully converted");
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("An error was found. {0}", e.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                progressBar.Visible = lblProgress.Visible = false;
                btnConvert.Enabled = true;
            }
        }

        private void SelectFiles_Load(object sender, EventArgs e)
        {
            cboConvertionType.Items.AddRange(Enum.GetNames(typeof(ConvertionType)));
            cboConvertionType.SelectedIndex = 0;
        }

        private void ConvertXlsToXlsb(string extension)
        {
            var xlsbFile = Path.Combine(txtDestination.Text, "{0}.xlsb");
            FilesToConvert = FilesInSourceFolder.Where(x => Path.GetExtension(x) == extension).ToList();

            foreach (var file in FilesToConvert)
            {
                ExcelHelper.ConvertXlsToXlsb(file, string.Format(xlsbFile, Path.GetFileNameWithoutExtension(file)));
                UpdateProgress(FilesToConvert.IndexOf(file));
            }
        }

        private void ConvertXlsToXlsx()
        {
            foreach (var file in FilesInSourceFolder.Where(x => Path.GetExtension(x) == ".xls"))
            {
                var xlsxFile = Path.Combine(txtDestination.Text, string.Concat(Path.GetFileNameWithoutExtension(file), ".xlsx"));
                Helpers.ExcelHelper.ConvertXlsToXlsb(file, xlsxFile);
            }
        }

        private void ConvertTxtToCsv()
        {
            foreach (var file in FilesInSourceFolder.Where(x => Path.GetExtension(x) == ".txt"))
            {
                var fileName = Path.GetFileNameWithoutExtension(file);

                Console.WriteLine("Converting file {0}", fileName);

                var content = File.ReadAllText(file, Encoding.GetEncoding(cultureInfo.TextInfo.ANSICodePage)).Replace(",", ".").Replace("|", ",");
                File.WriteAllText(Path.Combine(txtSource.Text, string.Concat(Path.GetFileNameWithoutExtension(file), ".csv")), content, Encoding.GetEncoding(cultureInfo.TextInfo.ANSICodePage));

                Console.WriteLine("Converted to {0}", string.Concat(Path.GetFileNameWithoutExtension(file), ".csv"));
            }
        }
    }
}
